package wahadlo.nowe.controllers;

import wahadlo.nowe.math.Algorithm;
import wahadlo.nowe.math.Euler;
import wahadlo.nowe.math.Function;
import wahadlo.nowe.model.Model;
import wahadlo.nowe.model.ModelRecipient;
import wahadlo.nowe.model.Point;
import wahadlo.nowe.model.StandardModel;
import wahadlo.nowe.utils.FunctionFactory;

class AnimationImpl implements Runnable, Animation {
	private boolean runnig = false;
	private Model model;
	private ModelRecipient modelRecipient;
	private boolean isResume;

	public void run() {
		long step = 15;
		Double cStep = 0.;

		String chartType = (String) model.getProperties().get("chartType");

		Function location = FunctionFactory.getFunction(chartType, model);

		Algorithm algorithm = new Euler(location.getValue(0.), (double) step);
		Double a0 = algorithm.getValue(location, cStep);

		while (runnig) {
			if (isResume)
				continue;
			StandardModel modelAndView = new StandardModel();
			a0 = algorithm.getValue(location, cStep);
			Point point = new Point(cStep, a0);
			cStep += 1;
			if (cStep > 500)
				stop();
			modelAndView.add("point", point);
			modelAndView.add("translation_scale", 5.);
			modelRecipient.setModel(modelAndView);
			modelRecipient.update();

			try {
				Thread.sleep(step);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void stop() {
		runnig = false;
	}

	public AnimationImpl(Model modelAndView, ModelRecipient modelRecipient) {
		this.model = modelAndView;
		this.modelRecipient = modelRecipient;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see wahadlo.nowe.controllers.Animation#isRunnig()
	 */
	public boolean isRunnig() {
		return runnig;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see wahadlo.nowe.controllers.Animation#setRunnig(boolean)
	 */
	public void setRunnig(boolean runnig) {
		this.runnig = runnig;
	}

	public void setResume(boolean isResume) {
		this.isResume = isResume;
	}

}
